package com.snowflake.ecatalog.web.admin;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.google.common.collect.Maps;
import com.snowflake.ecatalog.entity.CompanyCategory;
import com.snowflake.ecatalog.entity.CompanyCategoryStandard;
import com.snowflake.ecatalog.service.admin.CompanyCategoryService;
import com.snowflake.ecatalog.service.admin.CompanyCategoryStandardService;

/**
 * Task管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /category/ Create page : GET /category/create Create action :
 * POST /category/create Update page : GET /category/update/{id} Update action :
 * POST /category/update Delete action : GET /category/delete/{id}
 * 
 */
@Controller
@RequestMapping(value = "/category")
public class CompanyCategoryController {

	private static final int PAGE_SIZE = 10;

	@Autowired
	private CompanyCategoryService companyCategoryService;
	@Autowired
	private CompanyCategoryStandardService companyCategoryStandardService;

	@RequestMapping(value = "")
	public String list(@RequestParam(value = "standard", defaultValue = "0") long standardId,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model, ServletRequest request) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Map<Long, String> standards = getStandardSelect();
		if (standardId == 0) {
			standardId = Long.valueOf(standards.keySet().iterator().next());
		}
		Page<CompanyCategory> categorys = companyCategoryService.getCompanyCategorys(standardId, searchParams,
				pageNumber, PAGE_SIZE);
		model.addAttribute("categorys", categorys);
		model.addAttribute("standard", standardId);
		model.addAttribute("standards", standards);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return "admin/categoryList";
	}

	private Map<Long, String> getStandardSelect() {
		List<CompanyCategoryStandard> standards = companyCategoryStandardService
				.getEnabledCompanyCategoryStandard(null);
		Map<Long, String> select = Maps.newLinkedHashMap();
		for (CompanyCategoryStandard s : standards) {
			select.put(s.getId(), s.getName());
		}
		return select;
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("category", new CompanyCategory());
		model.addAttribute("action", "create");
		model.addAttribute("standards", companyCategoryStandardService.getAllCompanyCategoryStandard());
		return "admin/categoryForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid CompanyCategory newCategory, RedirectAttributes redirectAttributes) {
		companyCategoryService.saveCompanyCategory(newCategory);
		redirectAttributes.addFlashAttribute("message", "创建客户分类成功");
		return "redirect:/category/";
	}

	@RequestMapping(value = "enable/{id}")
	public String enable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		companyCategoryService.enableCompanyCategoryStandard(id);
		redirectAttributes.addFlashAttribute("message", "启用客户分类成功");
		return "redirect:/category/";
	}

	@RequestMapping(value = "disable/{id}")
	public String disable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		companyCategoryService.disableCompanyCategoryStandard(id);
		redirectAttributes.addFlashAttribute("message", "禁用客户分类成功");
		return "redirect:/category/";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		model.addAttribute("category", companyCategoryService.getCompanyCategory(id));
		model.addAttribute("action", "update");
		model.addAttribute("standards", companyCategoryStandardService.getAllCompanyCategoryStandard());
		return "admin/categoryForm";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadCompanyCategory") CompanyCategory category,
			RedirectAttributes redirectAttributes) {
		companyCategoryService.updateCompanyCategory(category);
		redirectAttributes.addFlashAttribute("message", "更新客户分类成功");
		return "redirect:/category/";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		// 校验是分类下是否关联客户档案
		if (existCompanyInCategory(id)) {
			redirectAttributes.addFlashAttribute("message", "该客户分类下已关联企业客户，不能删除");
		} else {
			companyCategoryService.deleteCompanyCategory(id);
			redirectAttributes.addFlashAttribute("message", "删除客户分类成功");
		}
		return "redirect:/category/";
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Goods对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadCompanyCategory")
	public CompanyCategory getCompanyCategory(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			CompanyCategory category = companyCategoryService.getCompanyCategory(id);
			category.setStd(null);
			return category;
		}
		return null;
	}

	private boolean existCompanyInCategory(Long cateforyId) {
		return companyCategoryService.existCompanyInCategory(cateforyId);
	}
}
